package com.dk.controller;

import com.dk.pojo.AjaxUser;
import com.dk.pojo.Role;
import com.dk.service.RoleService;
import com.dk.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("user")
public class AjaxUserController {
    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @RequestMapping("login")
    @ResponseBody
    public Integer loginInfo(AjaxUser user,String code, HttpServletRequest request){
        String c = (String) request.getSession().getAttribute("code");
       if (!code.equalsIgnoreCase(c)){
           return 5;
       }
        Integer i =  userService.loginInfo(user,request);
      return i;

    }
    @RequestMapping("loginOut")
    public String loginOut(HttpServletRequest request){
        request.getSession().removeAttribute("loginUser");
        return "redirect:/";
    }
    @RequestMapping("checkPhone")
    @ResponseBody
    public Boolean checkPhone(String uname){
        return userService.selectcheckPhone(uname);

    }
    @RequestMapping("register")
    @ResponseBody
    public Integer insertRe(AjaxUser user){
      return userService.insertRe(user);
    }
    @RequestMapping("toShow")
    public String toShow(){
        return "user/show";
    }
    @RequestMapping("getInfo")
    @ResponseBody
    public List<AjaxUser> getInfo(){
       List<AjaxUser> list =  userService.getInfo();
       return list;
    }
    @RequestMapping("toAdd")
    public  String toAdd(Model model){
        //查询所有角色
        List<Role> list = roleService.getInfo();
        model.addAttribute("list",list);
        return "user/add";
    }
    @RequestMapping("increase")
    @ResponseBody
    public boolean insertInfo(AjaxUser user,@RequestParam("rid")Integer[] rids){

        return userService.insertInfo(user,rids);
    }
    @RequestMapping("toUpdate/{uid}")
    public String toUpdate(Model model,@PathVariable("uid")Integer uid){
       AjaxUser user = userService.selectById(uid);
       List<Role> roles = roleService.selectRole();
       List<Integer> rids = roleService.selectUserRoleByUid(uid);
       model.addAttribute("user",user);
       model.addAttribute("roles",roles);
       model.addAttribute("rids",rids);
       return "user/update";
    }
    @RequestMapping("deleteById")
    @ResponseBody
    public boolean deleteById(Integer uid){
       int i = userService.deleteById(uid);
        return true;
    }
}


